from odoo import models, api
from datetime import timedelta
import pytz
from odoo.exceptions import UserError


class ReportPurchaseOrderSb(models.AbstractModel):
    _name = 'report.sb_workflow_purchase.label_purchase_order_untax_view_pdf'
    _description = 'Purchase Order Report'

    def convert_datetime_to_user_timezone(self, dt, to_tz, from_tz='UTC'):
        """
        将特定的datetime时间从一个时区转换到另一个时区

        :param dt: 要转换的datetime对象
        :param from_tz: 原始时区字符串（例如 'UTC'）
        :param to_tz: 目标时区字符串（例如 'Asia/Shanghai'）
        :return: 转换后的datetime对象
        """
        # 将原始datetime对象设置为原始时区
        from_timezone = pytz.timezone(from_tz)
        dt_with_tz = from_timezone.localize(dt)

        # 将datetime对象转换为目标时区
        to_timezone = pytz.timezone(to_tz)
        dt_converted = dt_with_tz.astimezone(to_timezone)

        return dt_converted

    @api.model
    def _get_report_values(self, docids, data=None):
        data_list = []
        purchase_ids = self.env['purchase.order'].browse(docids)
        lang = self.env.context.get('lang')
        for purchase in purchase_ids:
            partner_id = purchase.partner_id
            if not partner_id.child_ids:
                raise UserError(f'Vendor: {partner_id.name_en} No contact information is added')
            if not partner_id.vat:
                raise UserError(f'Vendor: {partner_id.name_en} No tax number is added')
            if not purchase.payment_term_id:
                raise UserError(f'No payment method is added')
            address = ''
            if partner_id.country_id:
                address += partner_id.country_id.name
            if partner_id.state_id:
                address += partner_id.state_id.name
            if partner_id.city:
                address += partner_id.city
            if partner_id.street:
                address += partner_id.street
            if partner_id.street2:
                address += partner_id.street2
            if partner_id.zip:
                address += partner_id.zip
            # 时区转换
            if purchase.date_planned:
                date_pl = self.convert_datetime_to_user_timezone(purchase.date_planned, self.env.context.get('tz'))
                date_planned = date_pl.strftime('%Y-%m-%d')
            else:
                date_planned = ''
            date_approve = purchase.date_approve
            if date_approve:
                # 交货日期
                delivery = self.convert_datetime_to_user_timezone(date_approve, self.env.context.get('tz'))
                delivery_date = delivery.strftime('%Y-%m-%d')
            else:
                delivery_date = ''
            tax_totals = purchase.tax_totals
            dtl = {
                'logo': '',
                'name': purchase.name,  # 订单编号
                'partner_name': partner_id.name_en,  # 供货方
                'address': address,  # 地址
                'date_order': delivery_date,  # 订单日期
                'user_id': purchase.user_id.name,  # 采购人
                'payment_term_id': purchase.payment_term_id.name,  # 付款方式
                'partner_ref': purchase.partner_ref,  # 编号
                'contact_name': '',  # 联系人
                'contact_mobile': '',  # 手机
                'contact_phone': '',  # 电话
                'control_no': purchase.requisition_id.name or '',  # 编号 (请购单号)
                'contact_fax': partner_id.vat,  # 税项ID
                'currency_id': purchase.currency_id.name,
                'tax_rate': ','.join(purchase.order_line.mapped('taxes_id.name')),
                'amount_total': tax_totals.get('formatted_amount_total'),
                'remark': purchase.s_remark or '',
                'contact_address': ''
            }
            # 联系人
            if partner_id.child_ids:
                contact_address = []
                contact = partner_id.child_ids[0]
                if contact.street:
                    contact_address.append(contact.street)
                if contact.street2:
                    contact_address.append(contact.street2)
                if contact.city:
                    contact_address.append(contact.city)
                if contact.state_id:
                    contact_address.append(contact.state_id.name)
                if contact.state_id:
                    contact_address.append(contact.zip)
                dtl.update({
                    'contact_name': contact.name,
                    'contact_mobile': contact.mobile,
                    'contact_phone': contact.phone,
                    'contact_address': ', '.join(contact_address)
                })
            data_line = []
            tax_amount = 0.0
            tax_subtotal = 0.0
            discounted = 0.0
            index = 1
            for line in purchase.order_line:
                if not line.product_id:
                    data_line.append({
                        'index': index,
                        'product_id': line.name,  # 产品名称
                        'product_code': '',  # 产品编码
                        'product_uom': '',  # 单位
                        'product_qty': '',  # 数量
                        'price_unit': '',  # 含税单价
                        'price_tax': '',  # 税额
                        'price_total': '',  # 含税金额
                        'untax_price_unit': '',  # 不含税单价
                        'price_subtotal': '',  # 不含税总额
                        'delivery_date': '',  # 交货日期
                        'remark': '',  # 备注
                    })
                    index += 1
                    continue
                price_unit_discounted = round(line.price_unit_discounted, 4)  # 单价折扣价格
                # 单价折扣金额 = 原价 - 折扣价格
                unit_dis = round(line.price_unit - price_unit_discounted, 4)
                # 折扣金额 = 单价折扣金额 * 数量
                unit_discounted = round(unit_dis * line.product_qty, 4)
                for tax in line.taxes_id:
                    tax_dis_unit = round(tax.amount * unit_discounted / 100, 4)
                    unit_discounted += tax_dis_unit
                discounted += unit_discounted
                # price_subtotal = line.price_subtotal  # 不含税总额
                # tax_subtotal += price_subtotal
                # price_tax = line.price_tax  # 税额
                # tax_amount += price_tax
                # price_total = line.price_total  # 含税总额
                # 含税单价 = 单价 + (税额 / 数量)
                # if line.product_qty > 0:
                #     price = line.price_unit + (price_tax / line.product_qty)
                # else:
                #     price = line.price_unit
                product_name = f'{line.product_id.name}（{line.product_id.description_eng or ""}）'
                data_line.append({
                    'index': index,
                    'product_id': product_name,  # 产品名称
                    'product_code': line.product_id.default_code,  # 产品编码
                    'product_uom': line.product_uom.name,  # 单位
                    'product_qty': line.product_qty,  # 数量
                    'price_unit': round(line.price_unit, 4),  # 未税单价
                    's_price_tax': round(line.s_price_tax, 4),  # 含税单价
                    'price_tax': round(line.price_tax, 2),  # 税额
                    'price_total': round(line.price_total, 2),  # 含税金额
                    'untax_price_unit': round(line.price_unit, 4),  # 不含税单价
                    'price_subtotal': round(line.price_subtotal, 2),  # 不含税总额
                    'delivery_date': date_planned,  # 交货日期
                    'remark': line.remark,  # 备注
                })
                index += 1
            # 说明（Explain）：
            explain = self.env['report.instructions'].search([('type', '=', 'purchase'), ('is_active', '=', True)])
            explain_list = [{'name': explain_line.content} for explain_line in explain]
            dtl.update({'order_line': data_line,
                        'tax_amount': round(tax_totals.get('amount_total') - tax_totals.get('amount_untaxed'), 2),
                        'tax_subtotal': tax_totals.get('formatted_amount_untaxed'),  # 不含税金额
                        'discounted': round(discounted, 2),  # 总折扣
                        'explain': explain_list.pop(0) if explain_list else {'name': ''},
                        'explain_list': explain_list
                        })
            data_list.append(dtl)
        return {
            'doc_model': 'purchase.order',
            'docs': docids,
            'data': data_list,
            'report_title': 'Purchase Order(PDF)',
        }
